<?php

namespace Goods\Logic;

use Think\Model\RelationModel;
/**
 * 购物车 逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class CartLogic extends RelationModel
{		
    /**
     * 加入购物车方法
     * @param type $goods_id  商品id
     * @param type $goods_num   商品数量
     * @param type $goods_spec  选择规格 
     * @param type $user_id 用户id
     */
    function addCart($goods_id,$goods_num,$goods_spec,$session_id,$user_id = 0)
    {       
        
        $goods = M('Goods')->where("goods_id = $goods_id")->find(); // 找出这个商品        

		$where = array("session_id"=>"$session_id");
        $user_id = $user_id ? $user_id : 0;
		if($user_id){
			$where['user_id'] = $user_id;
		}
		
		$catr_count = M('Cart')->where($where)->count(); // 查找购物车商品总数量		
        if($catr_count >= 20){ 
            return array('status'=>-9,'msg'=>'购物车最多只能放20种商品','result'=>'');            
        }
		
		$where['goods_id'] = $goods_id;
        
		if($goods_num <= 0){ 
            return array('status'=>-2,'msg'=>'购买商品数量不能为0','result'=>''); 
		}
		if($goods_num > 100){ 
            return array('status'=>-102,'msg'=>'单品数量不能超过100件','result'=>''); 
		}
		      
		
		//处理商品规格
		foreach($goods_spec as $vo){
			$spec_path = M('spec_item')->where(array("id"=>$vo))->find();
			$spec_item_name[] = $spec_path['item'];			
		}
		sort($goods_spec);
		$spec_item_name = implode(' ',$spec_item_name);//显示规格名
		$goods_spec_path = implode('-',$goods_spec);//规格规则
		$specGoodsSku = M('GoodsSku')->where(array("goods_id" => $goods_id,"item_path"=>$goods_spec_path))->find(); // 是否选择商品规格
		if(empty($specGoodsSku)){
			 return array('status'=>-101,'msg'=>'请选择规格','result'=>''); 
		}
		if($specGoodsSku['store_count'] <= 0){
			 return array('status'=>-99,'msg'=>'商品库存不足','result'=>'');
		}
		//print_r($specGoodsSku);
		//echo '<br>';
		//print_r($goods_spec_path);
		//die;
		if(!empty($goods_spec)){
			$where['spec_path'] = $goods_spec_path;
		}
		
        $catr_goods = M('Cart')->where($where)->find(); // 查找购物车是否已经存在该商品
		
		if($catr_goods['goods_num'] > 100){
			return array('status'=>-103,'msg'=>'单品数量不能超过100件','result'=>'');
		}
		if(($specGoodsSku['store_count'] <= $catr_goods['goods_num'])){
            return array('status'=>-4,'msg'=>'商品库存不足','result'=>'');
		}
      
        		
		if(!empty($specGoodsSku)){
			//有规格的商品超出存库
			if($goods_num > $specGoodsSku['store_count']){
				$goods_num = $specGoodsSku['store_count'];
			}			
		}else{
			//商品超出存库
			if($goods_num > $goods['store_count']){
				$goods_num = $goods['store_count'];
			}	
		}
		
        $data = array(                    
                    'user_id'         => $user_id,   // 用户id
                    'session_id'      => $session_id,   // sessionid
                    'goods_id'        => $goods_id,   // 商品id
					'goods_cat_id'    => $goods['cat_id'],   // 商品分类id
                    'goods_sn'        => $goods['goods_sn'],   // 商品货号
                    'goods_name'      => $goods['goods_name'],   // 商品名称
                    'market_price'    => $goods['market_price'],   // 市场价
                    'goods_price'     => $specGoodsSku['price'],  // 购买价
                    'member_goods_price' => $specGoodsSku['price'],  // 会员折扣价 默认为 购买价
                    'goods_num'       => $goods_num, // 购买数量
                    'spec_path'        => $goods_spec_path, // 规格key
                    'spec_item_name'   => $spec_item_name, // 规格 key_name
                   // 'sku'        => "{$specGoodsPriceList[$spec_key]['sku']}", // 商品条形码                    
                    'add_time'        => time(), // 加入购物车时间
                    'prom_type'       => $goods['prom_type'],   // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
                   // 'prom_id'         => $goods['prom_id'],   // 活动id                            
        );                

       // 如果商品购物车已经存在 
       if($catr_goods) 
       {     
			//是否存在规格
			if(!empty($catr_goods['spec_path'])){
				// 如果购物车的已有数量加上 这次要购买的数量  大于  库存输  则不再增加数量
				if(($catr_goods['goods_num'] + $goods_num) > $specGoodsSku['store_count']){
					$result = M('Cart')->where("id =".$catr_goods[id])->save(  array("goods_num"=> $specGoodsSku['store_count']) );
				}else{
					$result = M('Cart')->where("id =".$catr_goods[id])->save(  array("goods_num"=> ($catr_goods['goods_num'] + $goods_num)) ); // 数量相加        
				}
			}else{
				// 如果购物车的已有数量加上 这次要购买的数量  大于  库存输  则不再增加数量
				if(($catr_goods['goods_num'] + $goods_num) > $goods['store_count']){
					$result = M('Cart')->where("id =".$catr_goods[id])->save(  array("goods_num"=> $goods['store_count']) );
				}else{
					$result = M('Cart')->where("id =".$catr_goods[id])->save(  array("goods_num"=> ($catr_goods['goods_num'] + $goods_num)) ); // 数量相加        
				}
			}
			                           			
            $cart_count = cart_goods_num($user_id,$session_id); // 查找购物车数量 
            setcookie('cnum',$cart_count,null,'/');
			//cookie('cn',$cart_count);
            return array('status'=>1,'msg'=>'成功加入购物车','result'=>$cart_count,'item'=>$spec_item_name);
       }
       else
       {         
             $insert_id = M('Cart')->add($data);
             $cart_count = cart_goods_num($user_id,$session_id); // 查找购物车数量
             setcookie('cnum',$cart_count,null,'/');
			 //cookie('cn',$cart_count);
             return array('status'=>1,'msg'=>'成功加入购物车','result'=>$cart_count,'item'=>$spec_item_name);
       }     
            $cart_count = cart_goods_num($user_id,$session_id); // 查找购物车数量 
            return array('status'=>-5,'msg'=>'加入购物车失败','result'=>$cart_count);        
    }
    
    /**
     * 购物车列表 
     * @param type $user   用户
     * @param type $session_id  session_id
     * @param type $selected  是否被用户勾选中的 0 为全部 1为选中  一般没有查询不选中的商品情况
     * $mode 0  返回数组形式  1 直接返回result
     */
    function cartList($user_id, $session_id = '', $selected = 0,$mode =0)
    {                   
        
        		
        if($user_id)// 如果用户已经登录则按照用户id查询
        {
             $where['user_id'] = $user_id;
             // 给用户计算会员价 登录前后不一样             
        }           
        else
        {
            $where['session_id'] = $session_id;
            $user_id = 0;
        }
                                
        $cartList = M('Cart')->where($where)->select();  // 获取购物车商品 
        $anum = $total_price =  $cut_fee = 0;

        foreach ($cartList as $k=>$val){
        	$cartList[$k]['goods_fee'] = sprintf('%.2f',$val['goods_num'] * $val['member_goods_price']);
        	$cartList[$k]['store_count']  = getGoodNum($val['goods_id'],$val['spec_path']); // 最多可购买的库存数量        	
                $anum += $val['goods_num'];
                
                // 如果要求只计算购物车选中商品的价格 和数量  并且  当前商品没选择 则跳过
                if($selected == 1 && $val['selected'] == 0)
                    continue;
				
            $cut_fee += $val['goods_num'] * $val['member_goods_price']; //应付价格                                   
        	$total_price += $val['goods_num'] * $val['goods_price']; //商品总价
        }

        $total_price = array('total_fee' => sprintf('%.2f', $total_price), 'cut_fee' => sprintf('%.2f', $cut_fee),'num'=> $anum,); // 总计        
        setcookie('cnum',$anum,null,'/');
        if($mode == 1) return array('cartList' => $cartList, 'total_price' => $total_price);
        return array('status'=>1,'msg'=>'','result'=>array('cartList' =>$cartList, 'total_price' => $total_price));
    }    
	
	/**
     * 直接购买
     * @param type $goods_id  商品id
     * @param type $goods_num   商品数量
     * @param type $goods_spec  选择规格 
     */
	public function buyGoods($goods_id,$goods_num,$goods_spec){
		$goods = M('Goods')->where("goods_id = $goods_id")->find(); // 找出这个商品 
		
		$where['goods_id'] = $goods_id;
        
		if($goods_num <= 0){ 
            return array('status'=>-2,'msg'=>'购买商品数量不能为0','result'=>''); 
		}
		if($goods_num > 100){ 
            return array('status'=>-102,'msg'=>'单品数量不能超过100件','result'=>''); 
		}
		//处理商品规格
		foreach($goods_spec as $vo){
			$spec_path = M('spec_item')->where(array("id"=>$vo))->find();
			$spec_item_name[] = $spec_path['item'];			
		}
		
		sort($goods_spec);
		$spec_item_name = implode(' ',$spec_item_name);//显示规格名
		$goods_spec_path = implode('-',$goods_spec);//规格规则
		$specGoodsSku = M('GoodsSku')->where(array("goods_id" => $goods_id,"item_path"=>$goods_spec_path))->find(); // 是否选择商品规格
		if(empty($specGoodsSku)){
			 return array('status'=>-101,'msg'=>'请选择规格','result'=>''); 
		}
		if($specGoodsSku['store_count'] <= 0){
			 return array('status'=>-99,'msg'=>'商品库存不足','result'=>'');
		}
		
		$goods['item_name'] = $spec_item_name;
		$goods['spec_path'] = $goods_spec_path;
		$goods['buy_num'] = $goods_num;
		if(!empty($specGoodsSku)){
			//有规格的商品超出存库
			if($goods_num > $specGoodsSku['store_count']){
				$goods_num = $specGoodsSku['store_count']; //商品数量
			}			
		}else{
			//商品超出存库
			if($goods_num > $goods['store_count']){
				$goods_num = $goods['store_count'];
			}	
		}
				                                   
        $total_price += $goods_num * $goods['shop_price']; //商品总价       
		$cut_fee += $goods_num * $goods['shop_price']; //应付价格
		
        $total_price = array('total_fee' =>sprintf('%.2f', $total_price), 'cut_fee' => sprintf('%.2f', $cut_fee)); // 总计 
		session('sgoods',null);
		session('stotal_price',null);
		session('sgoods',$goods);
		session('stotal_price',$total_price);	
		return array('status'=>1);
	}
    
	/**
     * 添加订单
	 * @param type $user_id  用户id     
     * @param type $address_id 地址id
     * @param type $cart_price 应付金额
     * @param type $pay_status 支付方式
     */
	public function addOrder($user_id,$address_id,$cart_price,$pay_status,$to_buy=''){
		// 仿制灌水 1天只能下 50 单 
        $order_count = M('GoodsOrder')->where("user_id= $user_id and order_sn like '".date('Ymd')."%'")->count(); // 查找购物车商品总数量
        if($order_count >= 50) 
            return array('status'=>-9,'msg'=>'一天只能下50个订单','result'=>'');
		
		$address = M('UserAddress')->where("address_id = $address_id")->find();
		$data = array(
			'order_sn' => date('YmdHis').rand(1000,9999), // 订单编号
			'user_id' => $user_id, //用户id
			'consignee' => $address['consignee'], // 收货人
            'province' => $address['province'],//'省份id',
            'city' => $address['city'],//'城市id',
            'district' => $address['district'],//'县',
            'twon' => $address['twon'],// '街道',
            'address' => $address['address'],//'详细地址',
            'mobile' => $address['mobile'],//'手机',
			'invoice_title' => $invoice_title, //'发票抬头',  
			'goods_price' => $cart_price['payables'],//'商品总价'
			'order_amount' => $cart_price['payables'],//'应付款金额',暂无优惠券运费等金额
			'add_time' => time(), //下单时间			
			'pay_status' => $pay_status == 'cash' ? 3 : 0,
			'pay_name' => $pay_status == 'cash' ? '货到付款' : '',
		);
		$order_id = M("GoodsOrder")->data($data)->add();
		if(!$order_id)  
            return array('status'=>-8,'msg'=>'订单提交失败','result'=>NULL);
		
		// 记录订单操作日志
        logOrder($order_id,'您提交了订单，请等待系统确认','提交订单',$user_id);
		
		$order = M('GoodsOrder')->where("order_id = $order_id")->find(); 
		
		if($to_buy && $to_buy == 'buy'){
			//直接购买加入订单
			$s_goods = session('sgoods');
				$data2['order_id'] = $order_id; // 订单id
				$data2['goods_id'] = $s_goods['goods_id']; // 商品id
				$data2['goods_name'] = $s_goods['goods_name']; // 商品名称
				$data2['goods_sn'] = $s_goods['goods_sn']; // 商品货号(暂无)
				$data2['goods_num'] = $s_goods['buy_num']; // 购买数量
				$data2['market_price'] = $s_goods['market_price']; // 市场价
				$data2['goods_price'] = $s_goods['shop_price']; // 商品价格
				$data2['spec_path'] = $s_goods['spec_path']; // 商品规格
				$data2['spec_item_name'] = $s_goods['item_name']; // 商品规格名称
				$data2['member_goods_price'] = $s_goods['shop_price']; // 会员折扣价 暂无
				$order_goods_id = M("GoodsOrderSub")->data($data2)->add();
				session('sgoods',null);
				session('stotal_price',null);
		}else{
			//购物车加入订单
			$cartList = M('Cart')->where("user_id = $user_id and selected = 1")->select();
			foreach($cartList as $key => $v)
			{
				$goods = M('goods')->where("goods_id = {$v['goods_id']} ")->find();
				$data2['order_id'] = $order_id; // 订单id
				$data2['goods_id'] = $v['goods_id']; // 商品id
				$data2['goods_name'] = $v['goods_name']; // 商品名称
				$data2['goods_sn'] = $v['goods_sn']; // 商品货号
				$data2['goods_num'] = $v['goods_num']; // 购买数量
				$data2['market_price'] = $v['market_price']; // 市场价
				$data2['goods_price'] = $v['goods_price']; // 商品价格
				$data2['spec_path'] = $v['spec_path']; // 商品规格
				$data2['spec_item_name'] = $v['spec_item_name']; // 商品规格名称
				$data2['member_goods_price'] = $v['member_goods_price']; // 会员折扣价
				$order_goods_id = M("GoodsOrderSub")->data($data2)->add(); 
			}
			
			//删除购物车已提交订单商品
			M('Cart')->where("user_id = $user_id and selected = 1")->delete();
		}
		
		
		
        return array('status'=>1,'msg'=>'提交订单成功','result'=>$order_id); // 返回新增的订单id 
	}
	 
	
    /**
     * 查看购物车的商品数量
     * @param type $user_id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function cart_count($user_id,$mode = 0){
        $count = M('Cart')->where("user_id = $user_id and selected = 1")->count();
        if($mode == 1) return  $count;
        
        return array('status'=>1,'msg'=>'','result'=>$count);         
    }
    
   
}